<template>
  <a-modal v-model:open="isShow" title="编辑" @cancel="handleCancel" style="width: 700px">
    <a-spin :spinning="btnLoading">
      <a-form ref="form" :model="formState" :rules="rules" style="margin-top: 30px" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-item label="名称" name="itemText">
          <a-input v-model:value="formState.itemText" />
        </a-form-item>
        <a-form-item label="数据值" name="itemValue">
          <a-input v-model:value="formState.itemValue"  autocomplete="off" />
        </a-form-item>
        <a-form-item  label="描述" name="description">
          <a-input v-model:value="formState.description" autocomplete="off" />
        </a-form-item>
        <a-form-item  label="排序" name="sortOrder">
          <a-input-number v-model:value="formState.sortOrder"  autocomplete="off" />
        </a-form-item>
        <a-form-item  label="是否启用" name="status">
          <a-switch v-model:checked="formState.status"  checked-children="启用" un-checked-children="禁用" />
        </a-form-item>
      </a-form>
    </a-spin>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="btnLoading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import {reactive, computed, ref,watch} from 'vue'
import {message} from "ant-design-vue";
import {addDictItem, editDictItem} from "@/api/system/dict.js";
const props = defineProps({
  openEditItem:{
    type:Boolean,
  },
  dictId:{
    type:String,
  },
  records:{
    type:Object
  }
})
const emit = defineEmits(['close'])
const form = ref()
const formState = reactive({
  status: true,
  sortOrder:"1",
  itemValue:"",
  itemText:"",
  dictId:"",
})
const btnLoading = ref(false)
const isShow = computed(()=>{
  return props.openEditItem
})
const handleCancel = () => {
  emit('close')
}
const handleOk = async () => {
  try{
    const validate = await form.value.validate()
    try{
      btnLoading.value = true
      let obj = formState
      obj.status = obj.status === true ? "1" : "0"
      console.log(obj)
      const res = await editDictItem(obj)
      message.success("修改成功")
      emit('close')
      form.value.resetFields()
    }catch(e){
      message.error(e)
    }finally{
      btnLoading.value = false
    }
  }catch(e){
  }
}
const rules = {
  itemValue: [
    {required: true, message: '请输入数据值!',},
  ],
  itemText: [
    {required: true, message: '请重新输入名称!',},
  ],
}

watch(()=> props.openEditItem,()=>{
  if(props.openEditItem){
    for (let recordsKey in props.records) {
      formState[recordsKey] = props.records[recordsKey]
    }
    formState.dictId = props.dictId
    formState.status = formState.status == "1"
  }
  console.log(formState)
})
</script>
<style scoped>

</style>
